# coding: utf-8
from datetime import datetime
from sqlalchemy import CHAR, Column, String, text, func, DATETIME, ForeignKey
from sqlalchemy.dialects.mysql import INTEGER, TINYINT
from sqlalchemy.orm import relationship
from ..database import db,serialize
from .section import Section
from .roleuser import RoleUser


class Admin(db.Model):
    __tablename__ = 'admins'
    
    id = Column(INTEGER(11), primary_key=True,autoincrement = True)
    section_id = Column(INTEGER(11), ForeignKey('sections.id'), nullable=False)
    name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False,unique = True)
    realname = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
    email = Column(String(255, 'utf8mb4_unicode_ci'))
    password = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
    crypt = Column(CHAR(10, 'utf8mb4_unicode_ci'))
    phone = Column(String(20, 'utf8mb4_unicode_ci'), server_default=text("''"))
    lasttime = Column(DATETIME, server_default=func.now(), onupdate=func.now(), comment='最后登录时间')
    lastip = Column(String(15, 'utf8mb4_unicode_ci'), server_default=text("''"))
    status = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
    created_at = Column(DATETIME, default=datetime.now())
    updated_at = Column(DATETIME, default=datetime.now(),server_default=func.now(), onupdate=func.now(), comment='修改时间')
    # 关联部门类型
    section = relationship(
        'Section', backref='sections', uselist=False,lazy='joined')
    # 多对多角色
    role = relationship('RoleUser', foreign_keys=[RoleUser.user_id], backref=db.backref('roles', lazy='joined'), lazy='dynamic')
    
    # 查出来所有关联的用户
    @property
    def roles(self):
        from .role import Role
        return Role.query.join(RoleUser, RoleUser.role_id == Role.id).filter(RoleUser.user_id == self.id)
